<?php

// +----------------------------------------------------------------------
// | 版权所有 2017-2027 云南环拓科技有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.yn123.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// | 注意：  这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用,
// |        不允许对程序代码以任何形式任何目的的再发布。
// +----------------------------------------------------------------------
// | Author: feraner <feraner@163.com> 
// | Date: 2019/11/9
// +----------------------------------------------------------------------

namespace app\index\controller\api;

use app\common\constants\ApiConstant;
use app\common\facade\Arr;
use app\common\facade\Help;
use app\common\services\AdvertService;
use app\common\services\AliyunSmsServicer;
use app\common\services\AreaService;
use think\App;
use think\Db;

/**
 *
 * Class OtherCommon
 * @package app\index\controller\api
 * @author feraner<feraner@163.com>
 * @date 2019/11/9
 */
class OtherCommon extends ApiBase
{

    public function __construct(App $app = null)
    {
        parent::__construct($app);
    }


    /**
     * 地区列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function areaTree()
    {

        $treeList = (new AreaService())->getAreaTree();

        $this->response($treeList);
    }


    /**
     * 将经纬度转成系统中的地区ID
     */
    public function transLocation()
    {
        $latitude = $this->request->post('latitude', '');
        $longitude = $this->request->post('longitude', '');
        if ($latitude && $longitude) {
            $locationArr = Help::latLongToLocation($latitude, $longitude);
            if ($locationArr) {
                $this->response([
                    'areaValue'     => Arr::get($locationArr, 'provinceName') . '|' .
                        Arr::get($locationArr, 'cityName'),
                    'address'       => Arr::get($locationArr, 'address'),
                    'provinceName'  => Arr::get($locationArr, 'provinceName'),
                    'cityName'      => Arr::get($locationArr, 'cityName'),
                    'countyName'    => Arr::get($locationArr, 'countyName')
                ]);
            }
            $this->response(
                [],
                ApiConstant::API_ERROR,
                ApiConstant::API_ERROR_STR
            );
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
            );
    }





    /**
     * 获取两个经纬度之间的距离
     */
    public function getLocationDistance()
    {
        $fromLocation = $this->request->param('from');
        $toLocation = $this->request->param('to');
        if ($fromLocation && $toLocation) {
            $result = Help::computerDistance($fromLocation, $toLocation);
            if ($result) {
                $this->response([
                    'distance'      => round((Arr::get($result, 'distance') / 1000), 2),
                    'time'          => Arr::get($result, 'time')
                ]);
            }
            $this->response(
                [],
                ApiConstant::API_ERROR,
                ApiConstant::API_ERROR_STR
            );
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }


    /**
     * search  学校列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function searchSchool()
    {
        $searchText = $this->request->post('search', '', 'trim');
        $pageSize = $this->request->post('pageSize', 10);
        if ($searchText) {
            $result = Db::name('school')
                ->where('name', 'LIKE', '%' . $searchText . '%')
                ->order('id ASC')
                ->limit(0, $pageSize)
                ->select() ?: [];
            $schoolList = [];
            foreach ($result as $item) {
                array_push(
                    $schoolList,
                    [
                        'index'     => Arr::get($item, 'id'),
                        'text'      => Arr::get($item, 'name')
                    ]
                );
            }
            $this->response($schoolList);
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }


    /**
     * search 专业
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function searchMajor()
    {
        $searchText = $this->request->post('search', '');
        $pageSize = $this->request->post('pageSize', 10);
        if ($searchText) {
            $result = Db::name('school_major')
                ->where('name', 'LIKE', '%' . $searchText . '%')
                ->order('id ASC')
                ->limit(0, $pageSize)
                ->select() ?: [];
            $majorList = [];
            foreach ($result as $item) {
                array_push(
                    $majorList,
                    [
                        'index'     => Arr::get($item, 'id'),
                        'text'      => Arr::get($item, 'name')
                    ]
                );
            }
            $this->response($majorList);
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );

    }


    /**
     * 上传 base64 图片
     */
    public function uploadImg()
    {
        $savePath = $this->request->post('savePath', '');
        $base64Img = $this->request->post('img', '');
        $extend = $this->request->post('extend', '');
        if ($savePath && $base64Img) {
            $saveImg = '/upload/' . $savePath;
            $imgName = Help::saveBase64Img($base64Img, $saveImg);
            if ($imgName) {
                $this->response([
                    'img'           => $saveImg . $imgName,
                    'extend'        => $extend
                ]);
            } else {
                $this->response(
                    [],
                    ApiConstant::API_UPLOAD_IMG_ERROR,
                    ApiConstant::API_UPLOAD_IMG_ERROR_STR
                );
            }
        } else {
            $this->response(
                [],
                ApiConstant::API_PARAMETER_ERROR,
                ApiConstant::API_PARAMETER_ERROR_STR
            );
        }

    }


    /**
     * 获取系统中开放的地区
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function systemOpenArea()
    {
        $openAreaList = Db::name('system_agent_user')
            ->where('is_deleted', 0)
            ->where('status', 1)
            ->where('pid', 0)
            ->field('provinces_id,city_id,county_id')
            ->select() ?: [];

        $provincesIdArr = array_filter(array_column($openAreaList, 'provinces_id'));
        $cityIdArr = array_filter(array_column($openAreaList, 'city_id'));
        $countyIdArr = array_filter(array_column($openAreaList, 'county_id'));

        $provincesArr = Db::name('area')
            ->where('area_id', 'IN', $provincesIdArr)
            ->where('area_deep', 1)
            ->field('area_name,area_code')
            ->select() ?: [];

        $cityArr = Db::name('area')
            ->where('area_id', 'IN', $cityIdArr)
            ->where('area_deep', 2)
            ->field('area_name,area_code')
            ->select() ?: [];


        $countyArr = Db::name('area')
            ->where('area_parent_id', 'IN', $cityIdArr)
            ->where('area_deep', 3)
            ->field('area_name,area_code')
            ->select() ?: [];

        $provincesList = [];
        foreach ($provincesArr as $item) {
            if (Arr::get($item, 'area_code')) {
                $provincesList[Arr::get($item, 'area_code')] = Arr::get($item, 'area_name');
            }
        }

        $cityList = [];
        foreach ($cityArr as $item) {
            if (Arr::get($item, 'area_code')) {
                $cityList[Arr::get($item, 'area_code')] = Arr::get($item, 'area_name');
            }
        }


        $countyList = [];
        foreach ($countyArr as $item) {
            if (Arr::get($item, 'area_code')) {
                $countyList[Arr::get($item, 'area_code')] = Arr::get($item, 'area_name');
            }
        }

        $this->response([
            'province_list'     => $provincesList,
            'city_list'         => $cityList,
            'county_list'       => $countyList
        ]);


    }


    /**
     * 通过广告位置ID 来获取 banner
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function bannerItems()
    {
        $locationId = $this->request->param('locationId');

        $bannerItemList = (new AdvertService())->getAdvertList($locationId);

        $this->response($bannerItemList);

    }


    /**
     * 发送短信验证码
     * @throws \AlibabaCloud\Client\Exception\ClientException
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function sendSmsCode()
    {
        $phoneNum = $this->request->post('phone', '');
        if ($phoneNum) {

            //检测是否可以发送验证码
            $lastSendTime = session('smsCodeTime_' . $this->userId);
            if ($lastSendTime && ((time() - $lastSendTime) < 120)) {
                $this->response(
                    [],
                    ApiConstant::API_SEND_SMS_CODE_TOO_NEAR,
                    ApiConstant::API_SEND_SMS_CODE_TOO_NEAR_STR
                );
            } else {
                $code = rand(100000, 999999);
                try {
                    $result = (new AliyunSmsServicer())->sendSmsCode($phoneNum, $code);
                    if ($result) {
                        //添加session
                        session('smsCodeValue_' . $this->userId, $code);
                        session('smsCodeTime_' . $this->userId, time());
                        $this->response([]);
                    } else {
                        $this->response(
                            [],
                            ApiConstant::API_SEND_SMS_CODE_ERROR,
                            ApiConstant::API_SEND_SMS_CODE_ERROR_STR
                        );
                    }
                } catch (\Exception $e) {
                    $this->response(
                        [],
                        ApiConstant::API_ERROR,
                        ApiConstant::API_ERROR_STR . $e->getMessage()
                    );
                }
            }
        } else {
            $this->response(
                [],
                ApiConstant::API_PARAMETER_ERROR,
                ApiConstant::API_PARAMETER_ERROR_STR
            );
        }
    }


    /**
     * 充值活动详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function chargeActive()
    {
        $activeId = $this->request->param('id', 0);
        if ($activeId) {
            $activeInfo = Db::name('charge_active')
                ->where('id', $activeId)
                ->where('status', 1)
                ->where('start_time', '<=', time())
                ->where('end_time', '>=', time())
                ->find() ?: [];
            if ($activeInfo) {
                $this->response($activeInfo);
            } else {
                $this->response(
                    [],
                    ApiConstant::CHARGE_ACTIVE_NOT_FUND,
                    ApiConstant::CHARGE_ACTIVE_NOT_FUND_STR
                );
            }
        } else {
            $this->response(
                [],
                ApiConstant::API_PARAMETER_ERROR,
                ApiConstant::API_PARAMETER_ERROR_STR
            );
        }
    }



}
